/*
 * TITLE:AndroidMain
 * AUTHOR:Manori Thakur
 * PURPOSE: Communicates with ConnectServer class for request and response
 */

package clientcore;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
import java.io.IOException;

import com.example.android.debuggermenu.GameView;

import android.util.Log;

import clientrequest.*;
import clientresponse.ResponseFromServer;



public class AndroidMain {
	private static final String TAG = AndroidMain.class.getSimpleName();
    private short requestCode = 0;
    private short responseCode = 0;
    private ConnectServer cs;
    private DataOutputStream sendServer;
    private DataInputStream receiveServer;
    private Vector<Object> arguments = null;
    
    public AndroidMain() {
        cs = new ConnectServer(Constants.SERVER_IP,Constants.SERVER_PORT,this);  
        RequestToServerTable.init(this);
        ResponseFromServerTable.init(this);
        arguments = new Vector<Object>();
    }
    
    public boolean connectServer() {
    	return cs.connectServer();
    }

    /**
     * Sends request to game server
     * @param requestCode
     */
    public void sendRequest(short requestCode) {
    	Log.d(TAG, "Sending request with args: " + arguments);
        sendServer = cs.getDataOutputStream();
        RequestToServer request = RequestToServerTable.get(requestCode);
    	request.setOut(sendServer);
    	Log.d(TAG,"Request code to server: "+requestCode);
    	request.send(requestCode, arguments);
        cs.flushOutputStream();
        arguments.clear();
    }
    
    /**
     * Handles the response by the game server
     * @return
     */

    public short handleResponse() {
        receiveServer = cs.getDataInputStream();
        
        try {
            receiveServer.readByte(); //Reads the first two empty bytes sent by the server
            receiveServer.readByte();
            responseCode = (short)((receiveServer.readByte()& 0xFF)+(receiveServer.readByte()<< 8));
            ResponseFromServer response = ResponseFromServerTable.get(responseCode);
            Log.d(TAG,"Response code from server: "+responseCode);
            response.setIn(receiveServer);
            return response.process();

        }catch(IOException ex) {
            Log.e(TAG,"IO Exception in class AndroidMain in method handleResponse()"+ex.toString());
        }
        return -2;
    }

    public void setRequestCode(short code) {
        this.requestCode = code;
    }

    public short getRequestCode() {
        return requestCode;
    }

    public void addArguments(Object o) {
        arguments.add(o);
    }
    public String getArguments() {
        return arguments.toString();
    }
    
    public void closeServer() {
    	cs.closeServer();
    }  

}